package org.example.gift.controller;

import org.apache.commons.io.FilenameUtils;
import org.example.gift.service.ICommonService;
import org.example.gift.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/commons")
public class CommonController {

    @Value("${fastdfs.prefix}")
    private String prefix;

    @Autowired
    private ICommonService commonService;

    @PostMapping("/upload")
    public AjaxResult fileUpload(MultipartFile file) throws IOException {

        //从file里面获取后缀名
        String originalFilename = file.getOriginalFilename();//获取文件的原始名字
        //从原始名字里面获取后缀名  1. 分隔截取  2.在文件上传工具包里面有一个获取后缀名的方法
        String extName = FilenameUtils.getExtension(originalFilename);

        String upload = FastdfsUtil.upload(file.getBytes(), extName);
        //返回当前文件的访问路径
        return AjaxResult.success(prefix+upload);


    }
    @GetMapping("/imgCode/{uuid}")
    public AjaxResult imgCode(@PathVariable("uuid") String uuid){
        String code = commonService.createImgCode(uuid);

        return AjaxResult.success(code);
    }
    @PostMapping("/phoneCode")
    public AjaxResult phoneCode(@RequestBody PhoneCodeDto phoneCodeDto){
        commonService.sendPhoneCode(phoneCodeDto);
        return AjaxResult.success();
    }

}